/**
 * Created by Chen Kai on 2017/11/20.
 */

let Base64 = {
  characters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
  /**
   * string to blob
   * @param {string} string
   * @returns {string}
   */
  encode: function (string) {
    let characters = Base64.characters
    let result = ''

    let i = 0
    do {
      let a = string.charCodeAt(i++)
      let b = string.charCodeAt(i++)
      let c = string.charCodeAt(i++)

      a = a || 0
      b = b || 0
      c = c || 0

      let b1 = (a >> 2) & 0x3F
      let b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF)
      let b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3)
      let b4 = c & 0x3F

      if (!b) {
        b3 = b4 = 64
      } else if (!c) {
        b4 = 64
      }

      result += characters.charAt(b1) + characters.charAt(b2) + characters.charAt(b3) + characters.charAt(b4)

    } while (i < string.length)

    return result
  },

  /**
   * blob to string
   * @param {string} string
   * @returns {string}
   */
  decode: function (string) {
    let characters = Base64.characters
    let result = ''

    let i = 0
    do {
      let b1 = characters.indexOf(string.charAt(i++))
      let b2 = characters.indexOf(string.charAt(i++))
      let b3 = characters.indexOf(string.charAt(i++))
      let b4 = characters.indexOf(string.charAt(i++))

      let a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3)
      let b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF)
      let c = ((b3 & 0x3) << 6) | (b4 & 0x3F)

      result += String.fromCharCode(a) + (b ? String.fromCharCode(b) : '') + (c ? String.fromCharCode(c) : '')

    } while (i < string.length)

    return result
  }
}

/**
 * 节流函数
 * @param {Function} fn
 * @param {Number} delay
 * @param {Number} mustRunDelay
 * @returns {Function}
 */
function throttle (fn, delay, mustRunDelay = 0) {
  if (mustRunDelay) {
    let startTime = +new Date()
    return function () {
      const currentTime = +new Date()
      if (startTime && currentTime - startTime >= mustRunDelay) {
        startTime = +new Date()
        fn.apply(this, arguments)
      }
    }
  } else {
    let timer = null
    return function () {
      const context = this
      const args = arguments
      clearTimeout(timer)
      timer = setTimeout(function () {
        fn.apply(context, args)
      }, delay)
    }
  }
}

/**
 * 获取地址栏参数
 * @param key 参数名
 */
function getParam (key) {
  const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
  const r = window.location.search.substring(1).match(reg)
  return r ? decodeURI(r[2]) : null
}

/**
 * cookie操作
 * @example
 * getItem: docCookies.getItem(name)
 * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
 * docCookies.removeItem(name[, path], domain)
 * docCookies.hasItem(name)
 * docCookies.keys()
 */
const docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
      return false
    }
    let sExpires = ''
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + vEnd
          break
        case String:
          sExpires = '; expires=' + vEnd
          break
        case Date:
          sExpires = '; expires=' + vEnd.toUTCString()
          break
      }
    }
    document.cookie = encodeURIComponent(sKey) + '=' + encodeURIComponent(sValue) + sExpires + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '') + (bSecure ? '; secure' : '')
    return true
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !docCookies.hasItem(sKey)) {
      return false
    }
    document.cookie = encodeURIComponent(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '')
    return true
  },
  hasItem: function (sKey) {
    return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=')).test(document.cookie)
  },
  keys: function () {
    const aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, '').split(/\s*(?:\=[^;]*)?;\s*/)
    for (let nIdx = 0; nIdx < aKeys.length; nIdx++) {
      aKeys[nIdx] = decodeURIComponent(aKeys[nIdx])
    }
    return aKeys
  }
}

// 常用ua
// const uaStr = navigator.userAgent
// const ua = {
//   weibo: (/WeiBo/i).test(uaStr),
//   qq: (/QQBrowser/i).test(uaStr),
//   wechat: (/MicroMessenger/i).test(uaStr),
//   mobile: Boolean(uaStr.match(/AppleWebKit.*Mobile.*/)),
//   ios: Boolean(uaStr.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)),
//   iPhone: uaStr.indexOf('iPhone') > -1,
//   android: uaStr.indexOf('Android') > -1,
//   iPhoneX: false
// }
// if (/iphone/gi.test(navigator.userAgent) && (screen.availWidth === 375) && (screen.availHeight === 812)) {
//   ua.iPhoneX = true
// }

function rgbToHex (r, g, b) {
  const hex = ((r << 16) | (g << 8) | b).toString(16)
  return '#' + new Array(Math.abs(hex.length - 7)).join('0') + hex
}

function hexToRgb (hex) {
  const rgb = []
  for (let i = 1; i < 7; i += 2) {
    rgb.push(parseInt('0x' + hex.slice(i, i + 2)))
  }
  return rgb
}

// export {
//   ua,
//   throttle,
//   getParam,
//   docCookies,
//   Base64
// }

module.exports = {
  // ua: ua,
  throttle: throttle,
  getParam: getParam,
  docCookies: docCookies,
  Base64: Base64
}
